package cn.cxy.dbdemo

import android.content.ContentValues
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    private lateinit var dbHelper: DbHelper
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        dbHelper = DbHelper(this, "user_database", 1)

        addDataBtn.setOnClickListener { addUser() }
        updateDataBtn.setOnClickListener { updateUser() }
        delDataBtn.setOnClickListener { delUser() }
        queryDataBtn.setOnClickListener { queryUser() }
    }

    /**
     * 新增数据
     */
    private fun addUser() {
        val values = ContentValues().apply {
            put("user_name", "张三")
        }
        dbHelper.insert("user_table", values)
    }

    /**
     * 更新数据
     */
    private fun updateUser() {
        val values = ContentValues().apply {
            put("user_name", "李四")
        }
        dbHelper.update("user_table", values, null, null)
    }

    /**
     * 删除数据
     */
    private fun delUser() {
        dbHelper.deleteAll("user_table")
    }

    /**
     * 查询数据
     */
    private fun queryUser() {
        val cursor = dbHelper.query("user_table")
        if (cursor.moveToFirst()) {
            do {
                val id = cursor.getInt(cursor.getColumnIndex("_id"))
                val name = cursor.getString(cursor.getColumnIndex("user_name"))
                Log.d("MainActivity", "用户：${id}_$name")
            } while (cursor.moveToNext())
        } else {
            Log.d("MainActivity", "数据库是空的！")
        }
        cursor.close()
    }
}